package dm.ast;

import test.envset.GlobalState;

/**
 * select语句中的where子句
 */
public class DmWhere extends DmASTNode{

    DmBoolExpression whereExp = null;
    public int outerjoinwid = 0;

    public DmWhere() {

    }

    public DmWhere(DmBoolExpression boolExp) {
        whereExp = boolExp;
    }

    public DmBoolExpression getWhereExp() {
        return whereExp;
    }

    public void setBoolExpression(DmBoolExpression boolExp){
        whereExp = boolExp;
    }

    public boolean addWhereCondition(DmBoolOperator op){
        whereExp = DmBoolExpression.buildBoolExp(whereExp , op);
        return true;
    }

    public boolean addWhereCondition(DmBoolExpression boolExp , DmBoolOperator op){
        whereExp = DmBoolExpression.buildBoolExp(whereExp , boolExp ,op);
        return true;
    }


    @Override
    public void fill(GlobalState globalState) {
        if(!isCompleted){
            globalState.startWhere();
            whereExp.fill(globalState);
            globalState.finishWhere();
            isCompleted = true;
        }
    }

    public String toSql(){
        if(whereExp == null){
            return " " + this.getClass().getSimpleName();
        }else {
            StringBuilder sql = new StringBuilder();
            sql.append(whereExp.toSql());
            return String.format(" WHERE %s" , sql.toString());
        }
    }

    @Override
    public void setWidt() {
        if(whereExp == null){
            wid_t = 1;
        }else {
            wid_t = 1; //where关键字
            whereExp.setWidt();
            wid_t += whereExp.wid_t;
        }
    }

    @Override
    public void setDept() {
        if(whereExp != null){
            whereExp.setDept();
            dep_t = whereExp.dep_t;
        }else {
            dep_t = 1;
        }
    }

    @Override
    public DmDataType getExpressionType() {
        return null;
    }


    //处理sql错误
    //-4097|单行子查询返回多行
    public void fixErr4097(){
        DmExpression.fixErr4097Low(whereExp);
    }
}
